package config

import(
	// "nightowl/logger"
	. "nightowl/common"
	"io/ioutil"
    "gopkg.in/yaml.v2"
    "net/url"
    "os"
    "fmt"
    "regexp"
)
/**
 * 命令行参数
 */
type CmdArgs struct{
	Conf string
	LogLev string
	Port int
}
var CMD_ARGS *CmdArgs = &CmdArgs{
	Conf: "/opt/config/config.yaml",
	Port: 8083,
	LogLev: "INFO",
}
type CentralConfig struct{
	Server string `yaml:"server" json:"server"`
}
type AuthConfig struct{
	AccessKey string `yaml:"access-key" json:"access-key"`
	SecretKey string `yaml:"secret-key" json:"secret-key"`
}
type EdgeClientEnv struct{
	Name string `yaml:"name" json:"name"`
	Code string `yaml:"code" json:"code"`
	Server string `yaml:"server" json:"server"`
	Loc string `yaml:"loc" json:"loc"`
	Note string `yaml:"note" json:"note"`
	ResourcePoolCode string `yaml:"resourcePoolCode" json:"resourcePoolCode"`
}

//交付环境模型
type WorkConfig struct{
	FileServer string `yaml:"file-server" json:"file-server"`
	ImageServer string `yaml:"image-server" json:"image-server"`
	RootDir string `yaml:"root-dir" json:"root-dir"`
	RemoteShellRootDir string `yaml:"remote-shell-root-dir" json:"remote-shell-root-dir"`
}
/**
 * 配置文件绑定的结构体
 * eg:
 * 
 * central:
 *   server: http://127.0.0.1:8002  // 中央处理程序服务地址
 * edge-client:						// 当前边缘程序配置
 *   name: Client-01				// 边缘程序名
 *   code: client-01				// 边缘程编码
 *   server: http://127.0.0.1:8083	// 边缘服务地址
 *   loc: 北京						// 边缘地点
 *   note: 第一个客户端				// 说明
 *   resourcePoolCode: BEIJING_01	// 所在资源池编号
 * work:
 *   file-server: http://api.minio.thememories.cn:9000				// minio下载域名
 *   image-server: http://artifactory.dep.devops.cmit.cloud:20101	// 镜像地址域名
 *   root-dir: /opt/tmp												// 脚本运行目录
 *   remote-shell-root-dir: /opt/remote 							// 远程执行目录 scp目录
 * auth:
 *   access-key: ak-1	// 边缘节点分配的ak							
 *   secret-key: sk-1	// 边缘节点分配的sk
 * 
 */
type EnvConfig struct{
	EdgeClientEnv EdgeClientEnv `yaml:"edge-client" json:"edge-client"`
	WorkConfig WorkConfig `yaml:"work" json:"work"`
	AuthConfig AuthConfig `yaml:"auth" json:"auth"`
	CentralConfig CentralConfig `yaml:"central" json:"central"`
}
var ENV_CONFIG *EnvConfig
func LoadEnvConfig(){
	data, err := ioutil.ReadFile(CMD_ARGS.Conf)
    if err != nil {
        fmt.Printf("LoadEnvConfig|loadFile|error|%s", err)
        os.Exit(1)
        return
    }
    var result EnvConfig
    if err := yaml.Unmarshal(data, &result); err != nil {
        fmt.Printf("LoadEnvConfig|Unmarshal|error|%s", err)
        os.Exit(1)
        return
    }
    url, err := url.Parse(result.EdgeClientEnv.Server)
    if err == nil{
    	re := regexp.MustCompile(`(:\d+)?$`)
    	url.Host = re.ReplaceAllString(url.Host, fmt.Sprintf(":%d", CMD_ARGS.Port))
    	result.EdgeClientEnv.Server = url.String()
    	fmt.Printf("LoadEnvConfig|fix client server|server:%s\n", result.EdgeClientEnv.Server)
    }else{
    	fmt.Printf("LoadEnvConfig|parse client server|error|%s", err)
    }
    ENV_CONFIG = &result
    fmt.Printf("ENV_CONFIG:\n%s\n", ToYaml(*ENV_CONFIG))
}